var fs = require('fs')
var json = require('./yapi.json')

function writeApi(name, data) {
  let tpl = "\
\n\
  // %title\n\
  // %yapi\n\
  %name(sendData) {\n\
    return request.request({\n\
      url: '%url',\n\
      method: '%method',\n\
      %dataType: sendData,\n\
      loading: false,\n\
    })\n\
  },\n\
"

  function format(d) {
    let name, url, method, dataType, title, yapi
    yapi = `http://122.9.33.163:6300/project/${d.project_id}/interface/api/${d._id}`
    title = d.title
    method = d.method
    if (method.toLowerCase() === 'get') {
      dataType = 'params'
    } else {
      dataType = 'data'
    }
    url = d.path
    name = url.replace(/^[\w\W]*\//, '')

    return {
      name,
      url,
      method,
      dataType,
      title,
      yapi,
    }
  }

  function formatTpl(d, tpl) {
    for (let f1 in d) {
      let reg = new RegExp(`%${f1}`, 'g')
      tpl = tpl.replace(reg, d[f1])
    }
    return tpl
  }

  let str1 = ""
  let list = data.list

  for (let item of list) {
    let d = format(item)
    str1 += formatTpl(d, tpl)
  }

  str1 = `import request from '@/utils/request'\n\n//${name}\nconst api = \{\n${str1}\}\nexport default api`
  fs.writeFileSync(`./apijs/${name}api.js`, str1)
}

for (let item of json) {
  writeApi(item.name, item)
}
